﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sunboxsoft.Common;
using System.Data.SQLite;

namespace Sunboxsoft.ASMS.Client.Domain
{
    public class MasterDataStorage
    {
        public ServiceResult Sync()
        {
            WebRef.ASMSWebService service = RemoteInfo.GetASMSService();
            try
            {
                using (SQLiteConnection connection = new SQLiteConnection(SQLiteDatabase.ConnectionString))
                {
                    connection.Open();

                    SQLiteTransaction transaction = connection.BeginTransaction();

                    // 获取远程的主数据信息
                    WebRef.EMasterData[] mdArray = service.QueryMasterDataList().Data.Items;

                    // 检查本地是否存在
                    for (int index = 0; index < mdArray.Length; index++)
                    {
                        SingleResult<WebRef.EMasterData> localMD = new LocalService.GetService().GetMasterData(connection, mdArray[index].Code);
                        if (localMD.IsSuccess == false || localMD.Data == null || localMD.Data.Changeset < mdArray[index].Changeset)
                        {
                            // 更新本地的主数据
                            WebRef.EMasterDataItem[] items = service.QueryMasterDataItemList(mdArray[index].Code).Data.Items;

                            // 删除本地的记录
                            new LocalService.DeleteService().DeleteMasterDataAndItems(connection, mdArray[index].Code);
                            for (int itemIndex = 0; itemIndex < items.Length; itemIndex++)
                            {
                                new LocalService.CreateService().CreateMasterDataItem(connection, transaction, mdArray[index].Code, items[itemIndex].Code, items[itemIndex].ParentCode, items[itemIndex].Name, items[itemIndex].Pinyin, items[itemIndex].Letter, items[itemIndex].SortIndex, items[itemIndex].Tag);
                            }
                            // 生成新的数据
                            new LocalService.CreateService().CreateMasterData(connection, mdArray[index].Code, mdArray[index].Name, mdArray[index].Pinyin, mdArray[index].Letter, mdArray[index].Changeset);

                        }
                    }
                    transaction.Commit();
                }
            }
            catch (Exception ex)
            {
                return new ServiceResult(1, ex.Message);
            }
            finally
            {
                RemoteInfo.ReleaseASMSService(service);
            }


            return new ServiceResult();
        }
    }
}
